﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MyThreadShow
{
    public partial class Form4ManualResetEvent : Form
    {
        /*
         * 初始化同AutoResetEvent
         * 唯一不同 支持一个ManualResetEvent在多个在其之上等待的线程进行发送信号的操作
         
         */
        public Form4ManualResetEvent()
        {
            InitializeComponent();
            updateControl = UpdateLabel;
        }

        ManualResetEvent manualResetEvent = new ManualResetEvent(false);
        private void btnStartAThread_Click(object sender, EventArgs e)
        {
            StartThread1();
            StartThread2();
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            manualResetEvent.Set();
        }

        UpdateControl updateControl;

        void UpdateLabel(string message)
        {
            label1.Text += message + Environment.NewLine;
        }


        public void StartThread1()
        {
            Thread tWork = new Thread(() =>
            {
                this.BeginInvoke(updateControl, "线程1启动..");
                this.BeginInvoke(updateControl, "do something");
                this.BeginInvoke(updateControl, "start to wait for manualResetEvent 3s");

                manualResetEvent.WaitOne(3000);//设置等待时间

                this.BeginInvoke(updateControl, "end 线程1wait");
            });
            tWork.IsBackground = true;
            tWork.Start();
        }

        public void StartThread2()
        {
            Thread tWork = new Thread(() =>
            {
                this.BeginInvoke(updateControl, "线程2启动..");
                this.BeginInvoke(updateControl, "do something");
                this.BeginInvoke(updateControl, "start to wait for manualResetEvent");

                manualResetEvent.WaitOne();

                this.BeginInvoke(updateControl, "end 线程2wait");
            });
            tWork.IsBackground = true;
            tWork.Start();
        }
    }
}
